/*
 * @Author: c
 * @Date: 2023-12-03 02:18:10
 * @LastEditTime: 2024-01-14 20:04:47
 * @LastEditors: c
 * @Description: 用户端点
 * @FilePath: \music-web-backend\src\core\system\user\user.controller.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, Put, Query, Req, Request, Res, UploadedFile, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { createReadStream } from 'fs';
import { join } from 'path';
import { Roles } from 'src/common/decorators/roles.decorator';
import { PageResDto } from 'src/common/dto/page.dto';
import { Role } from 'src/common/enums/role.enum';
import { CreateUserDto, ResetUserPWD, UserForm } from './dto/create-user.dto';
import { UserPageQuery } from './dto/search-user.dto';
import { UserService } from './user.service';
import { UserPageVo } from './vo/user.vo';
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { }

  // user.controller.ts

  @Post('register')
  register(@Body() createUser: CreateUserDto) {
    return this.userService.singup(createUser);
  }

  @Roles(Role.Admin)
  @Get('getMyFav')
  getMyFav(@Body() createUser: CreateUserDto) {
    return this.userService.singup(createUser);
  }

  /**
   * 获取当前用户信息
   * @param req 
   * @returns 
   */
  @Get('me')
  getMyProfile(@Request() req) {

    return this.userService.getCurrentUserInfo(req.user.userId);
  }


  /**
   * 用户的列表-查询
   * @param pageDto 
   * @returns 
   */
  @Get('page')
  findAll(@Query() pageDto: UserPageQuery): Promise<PageResDto<UserPageVo>> {

    return this.userService.findAll(pageDto);
  }
  /**
   * 用户-新增
   * @param pageDto 
   * @returns 
   */
  @Post()
  saveUser(@Body() userForm: UserForm) {


    return this.userService.saveUser(userForm); //必须return 不然报错终止整个运行的进程
    
  }
  /**
   * 用户-修改
   * @param userForm 
   * @returns 
   */
  @Put(':userId')
  async updateUser(@Req() req, @Param('userId', ParseIntPipe) userId: number, @Body() userForm: UserForm) {

    return await this.userService.updateUser(req.user, userId, userForm); //必须return 不然报错终止整个运行的进程
  }

  /**
   * 用户-修改密码
   * @param userForm 
   * @returns 
   */
  @Patch(':userId/password')
  async updatePassword(@Param('userId', ParseIntPipe) userId: number, @Body() restPwd: ResetUserPWD) {


    return await this.userService.updatePassword(userId, restPwd.password); //必须return 不然报错终止整个运行的进程
  }

  /**
 * 用户-获取单条数据
 * @param typeCode 
 * @returns 
 */
  @Get(":userId/form")
  listDictOptions(
    @Param('userId') userId
  ) {
    return this.userService.getUserFormData(userId);

  }

  /**
   * 批量删除用户
   * @param ids 
   * @returns 
   */
  @Delete(':ids')
  removeIds(@Param('ids') ids: string) {
    return this.userService.deleteUsers(ids);
  }



  /**
   * 下载导入用户的excel模板
   * @param ids 
   * @returns 
   */
  @Get('template')
  // @Header('Content-Type', 'application/json')
  // @Header('Content-Disposition', `attachment; filename=${encodeURI('用户导入模板1.xlsx')}`)
  async downLoadExcelTemplate(@Res() res: Response): Promise<any> {

    //第一种基于流下载
    const file = createReadStream(join(process.cwd(), 'dist/resources/用户导入模板1.xlsx'));
    res.set({
      'Content-Type': 'application/json',
      'Content-Disposition': `attachment; filename=${encodeURI('用户导入模板1.xlsx')}`,
    });

    file.pipe(res);

    // //第二种基于压缩流的下载方式
    // // await this.userService.downloadTemplate(res);
    // const url = join(__dirname,'../../../resources/用户导入模板1.xlsx')
    // const tarStream  = new zip.Stream()
    // await tarStream.addEntry(url)

    // res.setHeader('Content-Type', 'application/octet-stream');

    // res.setHeader(
    //   'Content-Disposition',  
    //   `attachment; filename=xiaoman`,
    // );

    // tarStream.pipe(res)


    //第三种直接调用res.download 方法
    // res.setHeader(
    //   'Content-Disposition',
    //   `attachment; filename=xiaoman`,
    // );

    // const url = join(__dirname, '../../../resources/用户导入模板1.xlsx')
    // res.download(url, '用户导入模板1.xlsx')


  }

  /**
   * 批量导入用户
   * @param ids 
   * @returns 
   */
  @Post('_import')
  @UseInterceptors(FileInterceptor('file', { limits: { fieldSize: 10000 } })) //多文件使用@FileFieldsInterceptor
  async importUsers(@UploadedFile() file: Express.Multer.File) {

    return this.userService.importUsers(file);
  }
  /**
   * 导出用户Excel
   * @param ids 
   * @returns 
   */
  @Get('_export')
  async exportUsers(@Res() res: Response, @Query() userPage: UserPageQuery) {
    return this.userService.exportUsers(res, userPage);
  }

  // res.contentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  // res.setHeader("Content-Disposition", "attachment; filename=" + '用户列表.xlsx')
  // res.header("Content-Disposition", "attachment; filename=" + '用户列表.xlsx')
  // @Get("export")
  // @Header("Content-Disposition", 'attachment; filename="SheetJSNest.xlsx"')
  // async downloadXlsxFile(): Promise<StreamableFile> {
  //   var ws = utils.aoa_to_sheet(["SheetJS".split(""), [5, 4, 3, 3, 7, 9, 5]]);
  //   var wb = utils.book_new();
  //   utils.book_append_sheet(wb, ws, "Data");
  //   /* generate buffer */
  //   var buf = write(wb, { type: "buffer", bookType: "xlsx" });
  //   /* Return a streamable file */
  //   return new StreamableFile(buf);
  // }



  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.userService.findOne(+id);
  }



  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }
}

